/**
 * Lun management
 */

var lun = {
	/**
	 * Show Lun List
	 */
	list : function() {
		var poolListUrl = baseURL + "/cluster/lun/list"
		$.ajax({
			type : "get",
			url : poolListUrl,
			dataType : "html",
			success : function(html) {
				// Request successfully and fill the data.
				$("#content").empty().html(html);
			}
		});
	},

	/**
	 * Create new Lun
	 */
	create : function() {
		common.dialog({
			obj : "#createImageDialog",
			url : baseURL + "/cluster/lun/create",
			title : localeMsg.lun.create,
			width : 600,
			heigth : 300,
			confirm : function() {
				var data = $("#createImageForm").form('validate');
				if (data == true) {
					lun.createsave();
				} else {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.invalidData
					});
				}
			}
		});
	},
	/**
	 * CreateSave new Lun
	 */
	createsave : function() {
		$("#createImageForm").ajaxSubmit({
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.info,
						text : localeMsg.common.saveSuccess,
						success: true,
						callback : function() {
							lun.list();
						}
					});
				} else {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.saveFailed,
						success: false
					});
				}
			},
		});
	},
	/**
	 * Force_remove Lun
	 */
	force_remove : function() {
		// Remove more than one records
		// 用于选中复选框
		// push可以向数组的末位添加一个或多个元素并返回新的长度
		var infos = [];
		$('input[name="name"]:checked').each(function() {
			infos.push($(this).val());
		});
		if (infos == "") {
			common.showTip({
				title : localeMsg.common.warn,
				text : localeMsg.common.selectMsg
			});
		} else {
			common.confirmDialog(localeMsg.common.relateddeleteconfirm,function() {
				lun.confirmForceRemove();
			});
		}
	},
	confirmForceRemove : function(){
		var infos = [];
		$('input[name="name"]:checked').each(function() {
			infos.push($(this).val());
		});
		$.ajax({
			type : "post",
			url : baseURL + "/cluster/lun/force_remove",
			// 一个键值对
			data : {
				"infos" : infos
			},
			dataType : "json",
			// 删除数组
			traditional : true,
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.info,
						text : localeMsg.common.deleteSuccess,
						success: true,
						callback : function() {
							lun.list();
						}
					});
				} else {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.deleteFail,
						success: false
					});
				}
			}
		});
	},
	init :function(){
		
		$('#box').combobox({
			data : [
			        {"qosTypeId":0,
				      "qosType":"IOPS",
			        },
			        {"qosTypeId":1,
			      	"qosType":localeMsg.lun.bandWidth,} 
			        ],
			valueField : 'qosTypeId',
			textField : 'qosType',
			onSelect : function(record) {
				lun.change(record);
			},
		  onLoadSuccess: function () { //加载完成后,设置默认值
             /*var val = $(this).combobox("getData");
             for (var item in val[0]) {
                 if (item == "id") {
                     $(this).combobox("select", val[0][item]);
                 }
             }*/
			var qosType = $("#qosType").val();
			var val = $(this).combobox("getData");
			if(qosType==0){
				$('#box').combobox('setValue',val[0].qosTypeId);
			}else{
				$('#box').combobox('setValue',val[1].qosTypeId);
			}
         }
			
		});
		
	},
	
	change : function(record){
     var value = record.qosTypeId;
		if(value==0){
			$("#contentQos").empty().append("<input id='iopsId' type='hidden' name='qosType' value='"+value+"'/><table id='iopsTable'><tr><th style='width: 35%;' scope='row'>"+localeMsg.lun.readQos+"<span class='color_red'>*</span></th><td style='width: 85%;'>&nbsp;<input id='qosRead' type='text' name='qosRead' value=''/></td></tr><tr><th style='width: 35%;' scope='row'>"+localeMsg.lun.writeQos+"<span class='color_red'>*</span></th><td style='width: 85%;'>&nbsp;<input id='qosWrite' type='text' name='qosWrite' value=''/></td></tr></table>");
		}else{
			$("#contentQos").empty().append("<input id='bandwidthId' type='hidden' name='qosType' value='"+value+"'/><table id='bandwidthTable'><tr><th style='width: 35%;' scope='row'>"+localeMsg.lun.readQos+"<span class='color_red'>*</span></th><td style='width: 85%;'>&nbsp;<input id='qosRead' type='text' name='qosRead' value=''/></td></tr><tr><th style='width: 35%;' scope='row'>"+localeMsg.lun.writeQos+"<span class='color_red'>*</span></th><td style='width: 85%;'>&nbsp;<input id='qosWrite' type='text' name='qosWrite' value=''/></td></tr></table>");
		}
		var qosType = $("#qosType").val();
		var qosReadValue=$("#qosReadHidden").val();
		var qosWriteValue=$("#qosWriteHidden").val();
		if(value==qosType){
			$("#qosRead").val(qosReadValue);
			$("#qosWrite").val(qosReadValue);
		}
		if(value==0){
			lun.validateIops(); 
		}else{
			lun.validateBandWidth(); 
		}
	},
	
	qosByNameAndPoolName :function(){
		var qosTypeValue = $('#box').combobox('getValue');
		$("#qosForm").ajaxSubmit({
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : "Succeed to qos!",
						success: true,
						callback : function() {
							lun.list();
						}
					});
				}else if(json.result && json.result == "wrong"){
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.lun.exist+json.data+localeMsg.lun.noqos,
						//text :localeValidateMsg.exist,
						success: false
					});
				}else {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.saveFailed,
						success: false
					});
				}
			},
		});
	},
	/**
	 * 扩容
	 */
	modifyTotalSize :function(){
		
		var targetIds =[];
		$("input[name='name']:checked").each(function(){
			targetIds.push($(this).val()); 
            });
		var title = localeMsg.lun.enlarge;
		var param = {};
		if(targetIds.length==0){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else if(targetIds.length>1){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else{
			var targetId = $("input[name='name']:checked").val();
			param.targetId = targetId;
			common.dialog({
				obj : "#createImageDialog",
				type : "get",
				url : baseURL + "/cluster/lun/modifyTotalSize",
				param : param,
				title : title,
				width : 400,
				confirm : function() {
					if($("#saveTotalSizeForm").form('validate')!=true){
						return;
					}
					lun.saveTotalSize();
				}
			});
			
		}
		
	/*	
		var targetId = $("input[name='name']:checked").eq(0).val();
		
		var title = localeMsg.lun.Dilatate;
		var param = {};
		if (targetId && targetId != "") {
			param.targetId = targetId;
			common.dialog({
				obj : "#createImageDialog",
				type : "get",
				url : baseURL + "/cluster/lun/modifyTotalSize",
				param : param,
				title : title,
				width : 400,
				confirm : function() {
					if($("#saveTotalSizeForm").form('validate')!=true){
						return;
					}
					lun.saveTotalSize();
				}
			});
		}else{
			common.showTip({
				title : localeMsg.common.warn,
				text : localeMsg.common.selectMsg
			});
		}*/
	},
	
	
	/**
	 * 缩容
	 */
	reduceTotalSize :function(){
		
		var targetIds =[];
		$("input[name='name']:checked").each(function(){
			targetIds.push($(this).val()); 
            });
		var title = localeMsg.lun.reduceSize;
		var param = {};
		if(targetIds.length==0){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else if(targetIds.length>1){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else{
			var targetId = $("input[name='name']:checked").val();
			param.targetId = targetId;
			common.dialog({
				obj : "#createImageDialog",
				type : "get",
				url : baseURL + "/cluster/lun/reduceTotalSize",
				param : param,
				title : title,
				width : 400,
				confirm : function() {
					if($("#saveTotalSizeForm").form('validate')!=true){
						return;
					}
					lun.saveTotalSize();
				}
			});
			
		}
		
	
	},
	
	/**
	 * 显示lun映射的hosts
	 */
	showMappedHosts :function(type){
		
		var confirmText = localeMsg.common.confirm
		var lunIds =[];
		$("input[name='name']:checked").each(function(){
			lunIds.push($(this).val()); 
            });
		var title = localeMsg.host.list;
		var param = {};
		param.type = type;
		if (type=="mappedHostByLun") {
			confirmText = localeMsg.common.deleted;
		}
		
		if(lunIds.length==0){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else if(lunIds.length>1){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else{
			var lunId = $("input[name='name']:checked").val();
			param.lunId = lunId;
			common.dialog({
				//obj : "#createImageDialog",
				type : "get",
				url : baseURL + "/mapping/hostsList",
				param : param,
				title : title,
				width : 600,
				confirm : function(dialog) {
					var hostArr = [];
					$(dialog).find("input[name='hostId']:checked").each(function() {
						hostArr.push($(this).val());
					});
					if(!(hostArr.length>0)) {
						return;
					};
					lun.saveLunHosts(lunId, hostArr,type);
				},
				confirmText : confirmText
			});
			
		}
	
	},
	/**
	 * 保存lun-host关系
	 * @param groupId
	 * @param hostIdArr
	 */
	saveLunHosts : function(lunId, hostArr,type) {
		$.ajax({
			type : "post",
			url : baseURL + "/mapping/saveLunHosts",
			traditional: true,
			data : {lunId: lunId, hostIds : hostArr,type :type},
			dataType : "json",
			success : function(json) {
				/*common.showTip({
					title : localeMsg.common.prompt,
					text : localeMsg.common.saveSuccess,
					success : true
				});*/
				
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : localeMsg.common.saveSuccess,
						success: true
					});
				}else if(json.result && json.result == "wrong"){
					var names = "";
					for(var i=0; i<json.hostNames.length; i++)  
                       {  
                        names+= json.hostNames[i]+",";
                       }  
					names = names.substr(0,names.length - 1);
					common.showTip({
						title : localeMsg.common.warn,
						//text : "移除后"+names+"将不能与"+json.hostGroupNames+"映射",
						text : localeMsg.host.ifRemove+names+localeMsg.host.willNot+json.hostGroupNames+localeMsg.host.mapping,
						success: false
					});
				}else {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.saveFailed,
						success: false
					});
				}
				
				
				
				
			}
		});
	},
	/**
	 * 保存修改的容量
	 */
	saveTotalSize : function(){
		$("#saveTotalSizeForm").ajaxSubmit({
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.info,
						text : localeMsg.common.saveSuccess,
						success: true,
						callback : function() {
							lun.list();
						}
					});
				} else {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.saveFailed,
						success: false
					});
				}
			},
		});
	},
	
	
	/**
	 * qos
	 */
	qos : function() {
		
		
		
		var targetIds =[];
		$("input[name='name']:checked").each(function(){
			targetIds.push($(this).val()); 
            });
		var title = "Qos";
		var param = {};
		if(targetIds.length==0){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else if(targetIds.length>1){
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.common.selectMsg
			});
		}else{
			var targetId = $("input[name='name']:checked").val();
			title = "Qos";
			param.targetId = targetId;
			common.dialog({
				obj : "#createImageDialog",
				type : "get",
				url : baseURL + "/cluster/lun/qos",
				param : param,
				title : title,
				width : 400,
				confirm : function() {
					if($("#qosForm").form('validate')!=true){
						return;
					}
					lun.qosByNameAndPoolName();
				}
			});
			
		}
		
		
	},
	
	/**
	 * remove Lun
	 */
	remove : function() {
		var infos = [];
		$('input[name="name"]:checked').each(function() {
			infos.push($(this).val());
		});
		if (infos == "") {
			common.showTip({
				title : localeMsg.common.warn,
				text : localeMsg.common.selectMsg
			});
		} else {
			common.confirmDialog(localeMsg.common.deletetorecycle,function() {
				lun.confirmRemove();
			});
		}
	},
	confirmRemove : function(){
		var infos = [];
		$('input[name="name"]:checked').each(function() {
			infos.push($(this).val());
		});
		$.ajax({
			type : "get",
			url : baseURL + "/cluster/lun/remove",
			// 一个键值对
			data : {
				"infos" : infos
			},
			dataType : "json",
			traditional : true,
			success : function(json) {
				if (json.result && json.result == "success") {
						common.showTip({
							title : localeMsg.common.info,
							text : localeMsg.common.deleteSuccess,
							success: true,
							callback : function() {
								lun.list();
							}
						});
					}else {
						common.showTip({
							title : localeMsg.common.warn,
							text : localeMsg.common.deleteFail,
							success: false
					});
				}
			}
		});
	},
	/**
	 * validate form
	 */
	validate : function(){
		// poolName 验证非空，
		$('#name').validatebox({
			required : true,
			// 在页面取所有的name与传进来的value值比较
			validType : 'imagename'
		});
		// size 验证非空,小与对应pool的最大容量
		$('#size').validatebox({
			required : true,
			validType : 'size' 
		});
	},

	/**
	 * validate size
	 */
	/*validateSize : function(){
		var oldSize = $("#size").val();
		// size 验证非空，为oldSize-10之间整数
		$('#size').validatebox({
			required : true,
			validType : [ 'number['+oldSize+',10]', 'positive_integer']
		});
	},*/
	validateSize : function(){
		var oldSize = $("#size").val();
		// size 验证非空，为大于oldSize的整数
		$('#size').validatebox({
			required : true,
			validType : [ 'numbermore['+oldSize+']', 'positive_integer']
		});
	},
	validateReduceSize : function(){
		var oldSize = $("#size").val();
		// size 验证非空，为小于oldSize的整数
		$('#size').validatebox({
			required : true,
			validType : [ 'numberless['+oldSize+']', 'positive_integer']
		});
	},
	/**
	 * validate iops和bandwidth长度
	 */
	/*validateQos : function(){
		// qosRead 验证非空，
		$('#qosRead').validatebox({
			required : true,
			// 在页面取所有的qosRead与传进来的qosRead值比较
			validType :  'iopsLength'
		});
		
		$('#qosWrite').validatebox({
			required : true,
			// 在页面取所有的qosWrite与传进来的qosWrite值比较
			validType :  'bandwidthLength'
		});
		
	},*/
	validateIops : function(){
		$('#qosRead,#qosWrite').validatebox({
			required : true,
			// 在页面取所有的qosRead,qosWrite与传进来的qosRead,qosWrite值比较
			validType :  ['iopsLength','positive_integer']
		});
	},
	validateBandWidth : function(){
		$('#qosRead,#qosWrite').validatebox({
			required : true,
			// 在页面取所有的qosRead与传进来的qosRead值比较
			validType :  ['bandwidthLength','positive_integer']
		});
	},
	/**
	 * 同步lun信息
	 */
	sync : function() {
		$.ajax({
			type : "post",
			url : baseURL + "/cluster/lun/sync",
			dataType : "json",
			success : function(json) {
				common.showTip({
					title : localeMsg.common.info,
					text : localeMsg.lun.syn,
					success: true,
					callback : function() {
						lun.list();
					}
				});
			}
		});
	}
};
